package com.bailian.app.controller.Apis;

import com.bailian.app.controller.BaseAppController;
import com.bailian.common.core.domain.AjaxResult;
import com.bailian.common.core.page.TableDataInfo;
import com.bailian.common.utils.bean.BeanUtils;
import com.bailian.system.domain.BlMyFavorite;
import com.bailian.system.domain.BlNews;
import com.bailian.system.domain.BlPark;
import com.bailian.system.domain.vo.BlMyFavoriteVo;
import com.bailian.system.domain.vo.BLWareHouseVo;
import com.bailian.system.domain.vo.BlParkVo;
import com.bailian.system.service.IBlMyFavoriteService;
import com.bailian.system.service.IBlNewsService;
import com.bailian.system.service.IBlWarehouseService;
import com.bailian.system.service.IBlParkService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 收藏控制器
 * 
 * @author bailian
 */
@Api(tags = "收藏相关接口")
@RestController
@RequestMapping("/app/api/favorite")
public class FavoriteController extends BaseAppController {

    @Autowired
    private IBlMyFavoriteService favoriteService;

    @Autowired
    private IBlNewsService newsService;

    @Autowired
    private IBlWarehouseService warehouseService;

    @Autowired
    private IBlParkService parkService;

    /**
     * 添加收藏
     */
    @ApiOperation("添加收藏")
    @PostMapping("/add")
    public AjaxResult addFavorite(@RequestBody BlMyFavorite params) {
        try {
            // 获取当前用户ID（拦截器已验证token）
            Long userId = getCurrentUserId();
            // 获取参数
            Long contentId = params.getContentId();
            Integer contentType = params.getContentType();
            String title = params.getTitle();
            String desc = params.getDesc(); 
            if (contentId == null || contentType == null) {
                return error("内容ID和内容类型不能为空");
            }
            
            // 添加收藏
            int result = favoriteService.addFavorite(userId, contentId, contentType, title, desc);
            
            if (result > 0) {
                return success("收藏成功");
            } else if (result == 0) {
                return error("该内容已收藏");
            } else {
                return error("收藏失败");
            }
        } catch (Exception e) {
            return error("收藏失败：" + e.getMessage());
        }
    }
    
    /**
     * 取消收藏
     */
    @ApiOperation("取消收藏")
    @DeleteMapping("/cancel")
    public AjaxResult cancelFavorite(@RequestBody BlMyFavorite params) {
        try {
            // 获取当前用户ID（拦截器已验证token）
            Long userId = getCurrentUserId();
            
            // 获取参数
            Long contentId = params.getContentId();
            Integer contentType = params.getContentType();
            
            if (contentId == null || contentType == null) {
                return error("内容ID和内容类型不能为空");
            }
            
            // 取消收藏
            int result = favoriteService.cancelFavorite(userId, contentId, contentType);
            
            if (result > 0) {
                return success("取消收藏成功");
            } else {
                return error("取消收藏失败");
            }
        } catch (Exception e) {
            return error("取消收藏失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取收藏列表
     */
    @ApiOperation("获取收藏列表")
    @GetMapping("/list")
    public TableDataInfo getFavoriteList(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam("页大小") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam("内容类型") @RequestParam(required = false) Integer contentType) {
        
        try {
            // 获取当前用户ID（拦截器已验证token）
            Long userId = getCurrentUserId();
            
            startPage();
            BlMyFavorite favorite = new BlMyFavorite();
            favorite.setUserId(userId);
            if (contentType != null) {
                favorite.setContentType(contentType);
            }
            List<BlMyFavorite> list = favoriteService.selectBlMyFavoriteList(favorite);
            List<BlMyFavoriteVo> listVo = new ArrayList<>();
            for (BlMyFavorite item : list) {
                BlMyFavoriteVo vo = new BlMyFavoriteVo();
                BeanUtils.copyProperties(item, vo);
                listVo.add(vo);
                if (item.getContentType() == 0) {
                    BlNews news = newsService.selectBlNewsById(item.getContentId());
                    vo.setNews(news);
                } else if (item.getContentType() == 1) {
                    BLWareHouseVo warehouse = warehouseService.selectBlWarehouseVoByWarehouseId(item.getContentId());
                    vo.setWarehouse(warehouse);
                } else if (item.getContentType() == 2) {
                    BlParkVo park = parkService.selectById(item.getContentId());
                    vo.setPark(park);
                }
            }
            return getDataTable(listVo);
        } catch (Exception e) {
            throw new RuntimeException("获取收藏列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查是否已收藏
     */
    @ApiOperation("检查是否已收藏")
    @PostMapping("/check")
    public AjaxResult checkFavorite(@RequestBody Map<String, Object> params) {
        
        try {
            // 获取当前用户ID（拦截器已验证token）
            Long userId = getCurrentUserId();
            
            // 获取参数
            Long contentId = Long.valueOf(params.get("contentId").toString());
            Integer contentType = Integer.valueOf(params.get("contentType").toString());
            
            if (contentId == null || contentType == null) {
                return error("内容ID和内容类型不能为空");
            }
            
            // 检查是否已收藏
            boolean isFavorited = favoriteService.isFavorited(userId, contentId, contentType);
            
            Map<String, Object> result = new HashMap<>();
            result.put("isFavorited", isFavorited);
            
            return success(result);
        } catch (Exception e) {
            return error("检查收藏状态失败：" + e.getMessage());
        }
    }
} 